<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-button type="primary" @click="addclassification">添加分类</el-button>
            <!-- :columns(设置表格中列配置信息) -->
            <!-- selection-type	是否为多选类型表格 去掉前面的多选框-->
            <!-- expand-type	是否为展开行类型表格 -->
            <!-- show-index	是否显示数据索引 -->
            <!-- index-text	数据索引名称 -->
            <!-- border	是否显示纵向边框 -->
            <tree-table :data="CategoriesData" :columns="columns" :selection-type="false" :expand-type="false" show-index index-text="#" border>
                <template slot-scope="scope" slot="isOK">
                    <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen"></i>
                    <i class="el-icon-error" v-else style="color: red"></i>
                </template>
                <template slot="level" slot-scope="scope">
                    <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
                    <el-tag v-else-if="scope.row.cat_level === 1" type="success" size="mini">二级</el-tag>
                    <el-tag v-else-if="scope.row.cat_level === 2" type="warning" size="mini">三级</el-tag>
                </template>
                <template slot="operation" slot-scope="scope">
                    <el-button type="primary" size="mini" @click="editput(scope.row)">
                        <i class="el-icon-edit"></i>
                        编辑
                    </el-button>
                    <el-button type="danger" size="mini" @click="daleteshop(scope.row)">
                        <i class="el-icon-delete"></i>
                        删除
                    </el-button>
                </template>
            </tree-table>
            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="categorieslist.pagenum" :page-sizes="[5, 10, 15, 20]"
                :page-size="categorieslist.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="commodityTotal">
            </el-pagination>
        </el-card>
        <!-- 添加分类对话框 -->
        <el-dialog title="添加分类" :visible.sync="addclassificationVisible" width="50%" @close="closeaddclass">
            <div>
                <el-form ref="addclassRef" :model="addclassform" label-width="100px" :rules="addclassrules">
                    <el-form-item label="分类名称:" prop="cat_name">
                        <el-input v-model="addclassform.cat_name"></el-input>
                    </el-form-item>
                    <el-form-item label="父级分类">
                        <!-- change能拿到v-model双向绑定的数据 -->
                        <!-- props中规定了显示的数据为cat_name 传递为children -->
                        <!-- clearable	是否支持清空选项 -->
                        <!-- 1.change-on-select让里面的每一项都可以选择 -->
                        <!-- 2.可通过 props.checkStrictly = true 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的。 -->
                        <!-- 1和2作用相同 -->
                        <el-cascader style="width:100%" clearable v-model="regulationsvalue" expandTrigger='hover' :options="getaddoptions" :props="regulationsprops" @change="addregulationsChange"></el-cascader>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addclassificationVisible = false">取 消</el-button>
                <el-button type="primary" @click="Addcategory">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑对话框 -->
        <el-dialog title="修改分类" :visible.sync="editVisible" width="50%">
            <!-- rules 校验规则 -->
            <div>
                <el-form :rules="editrules" :model="editModel" ref="editRef" label-width="100px">
                    <el-form-item label="分类名称:" prop="cat_name">
                        <el-input v-model="editModel.cat_name"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="editover">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                CategoriesData:[],
                // 请求参数
                categorieslist:{
                    type:[],
                    pagenum:1,
                    pagesize:5
                },
                columns:[
                    {label:'分类名称',prop:'cat_name'},
                    {label:'是否有效',
                    prop:'at_deleted',
                    // 表示，将当前列定义为模版
                    type: 'template',
                    // 表示当前这一列使用模版名称
                    template: 'isOK'},
                    {
                        label:'排序',
                        prop:'cat_level',
                        type:'template',
                        template:'level'
                    },
                    {
                        label:'操作',
                        type:'template',
                        template:'operation'
                    }
                ],
                // 总页数
                commodityTotal:0,
                addclassificationVisible: false,
                addclassform:{
                    cat_name:'',
                    cat_pid:0,
                    // cat_pid   | 分类父 ID | 不能为空，如果要添加1级分类，则父分类Id应该设置为  `0
                    cat_level:0
                    // cat_level | 分类层级  | 不能为空，`0`表示一级分类；`1`表示二级分类；`2`表示三级分类
                },
                addclassrules:{
                    cat_name:[
                        {required: true, message: '请输入分类名称', trigger: 'blur' }
                    ]
                },
                getaddoptions:[],
                regulationsprops:{
                    value:'cat_id',
                    label:'cat_name',
                    children:'children',
                    checkStrictly: true
                },
                regulationsvalue:[],
                // 控制编辑对话框的显示
                editVisible: false,
                // 校验规格数据
                editModel:{
                    cat_name:''
                },
                editrules:{
                    cat_name:[
                        {required: true, message: '请输入分类名称', trigger: 'blur' }
                    ]
                },
                shuju:{}
            }
        },
        created() {
            this.getCategories()
        },
        methods:{
            async getCategories() {
                const {data: res}= await this.$http.get('categories',{
                    params: this.categorieslist
                })
                // console.log(res);
                if(res.meta.status !== 200)return this.$message.error(res.meta.msg)
                this.CategoriesData = res.data.result
                this.commodityTotal = res.data.total
            },
            handleSizeChange(newsize) {
                // console.log(newsize);
                this.categorieslist.pagesize = newsize
                this.getCategories()
            },
            handleCurrentChange(newcurr) {
                this.categorieslist.pagenum = newcurr
                this.getCategories()
            },
            // 添加分类按钮
            addclassification() {
                this.getaddoptionsly()
                this.addclassificationVisible = true
            },
            // 获取级联选择器需要的两层数据
            async getaddoptionsly() {
                const {data: res} = await this.$http.get('categories',{
                    params: {type:2}
                })
                if(res.meta.status !== 200) {
                    this.$message.error(res.meta.msg)
                }
                // console.log(res.data);
                this.getaddoptions = res.data
            },
            // 能拿到v-model绑定的值  难点
            addregulationsChange() {
                console.log(this.regulationsvalue);
                if(this.regulationsvalue.length > 0){
                    // 当前的父级ID
                    this.addclassform.cat_pid = this.regulationsvalue[this.regulationsvalue.length-1]
                    // 当前的层级
                    this.addclassform.cat_level = this.regulationsvalue.length
                    return
                }else {
                    // 当前的父级ID
                    this.addclassform.cat_pid = 0
                    // 当前的层级
                    this.addclassform.cat_level = 0
                }
            },
            Addcategory() {
                // console.log(this.addclassform);
                // validate
                this.$refs.addclassRef.validate(async vail=>{
                    console.log(vail);
                    if(!vail) return
                    const {data: res}=await this.$http.post('categories',this.addclassform)
                    // console.log(res);
                    if(res.meta.status !== 201)return this.$message.error(res.meta.msg)
                    this.$message.success('添加分类成功')
                    this.getCategories()
                    this.addclassificationVisible = false
                })
            },
            // 监听关闭from表单把数据清零 难点
            closeaddclass() {
                this.$refs.addclassRef.resetFields();
                this.regulationsvalue = []
                this.addclassform.cat_pid= 0
                this.addclassform.cat_level = 0
            },
            //编辑函数
            editput(roles) {
                this.shuju = roles
                // console.log(roles);
                this.editModel.cat_name = roles.cat_name
                this.editVisible = true
            },
            editover() {
                // 确定预校验
                this.$refs.editRef.validate(async vail=>{
                    // console.log(this.editModel.cat_name);
                    // console.log(this.shuju.cat_id);
                    if(!vail)return 
                    const {data: res}= await this.$http.put(`categories/${this.shuju.cat_id}`,{cat_name:this.editModel.cat_name})
                    console.log(res);
                    if(res.meta.status !== 200)return this.$message.error(res.meta.msg)
                    this.$message.success('修改分类名称成功')
                    this.getCategories()
                    this.editVisible = false
                })
            },
            // 删除
            async daleteshop(roles) {
                const res=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                // console.log(res);
                if(res !=='confirm'){
                    return this.$message.info('已取消删除')
                }
                const {data: msg}= await this.$http.delete(`categories/${roles.cat_id}`)
                // console.log(msg);
                if(msg.meta.status !== 200) {
                    return this.$message.error(msg.meta.msg)
                }
                this.getCategories()
            }
        }
    }
</script>
<style lang="less" scoped>
.zk-table {
    margin-top: 15px;
}
.el-radio {
    visibility: hidden;
}
</style>